import { feedApi } from '/api/feed'
import { GlobalData } from '/store/state'
import { $event } from '/utils'

Page({
  data: {
    isFullScreen: GlobalData.isFullScreen,
    title: '' as string,
    content: '' as string,
    iseditor: false,
    /** 点击锁 */
    publishing: false,
    theme: {} as DomoTheme,
  },
  onLoad(Options) {
    if (Options.iseditor) {
      wx.setNavigationBarTitle({ title: '编辑话题' })
      const pages = getCurrentPages()
      const lastPage = pages[pages.length - 2]
      this.setData({
        theme: lastPage.data.theme,
        iseditor: !!Options.iseditor,
        title: lastPage.data.theme.title,
        content: lastPage.data.theme.description,
      })
    }
    this.setData({
      isFullScreen: GlobalData.isFullScreen,
    })
  },
  /** 输入话题名 */
  inputTitle(e: WechatMiniprogram.Input) {
    const title = e.detail.value
    this.setData({
      title,
    })
  },
  /** 输入话题描述 */
  inputContent(e: WechatMiniprogram.Input) {
    const content = e.detail.value
    this.setData({
      content,
    })
  },
  submit() {
    const { iseditor, title, content: description, theme } = this.data

    if (!title || !description) {
      wx.showToast({
        title: '请完善所有信息',
      })
      return
    }
    this.setData({
      publishing: true,
    })
    /** 创建 */
    if (!iseditor) {
      feedApi
        .CreatTheme({ title: title, description: description })
        .then((res) => {
          wx.showToast({
            title: '创建成功',
            duration: 1000,
          })
          setTimeout(() => {
            wx.redirectTo({
              url: `/pages/theme/detail/detail?id=${res.id}`,
            })
          }, 1000)
        })
        .catch((err) => {
          wx.showToast({
            title: `${err.massage}`,
            icon: 'none',
          })
          this.setData({
            publishing: true,
          })
        })
    } else {
      /** 编辑 */
      if (title === theme.title && description === theme.description) {
        this.setData({
          publishing: false,
        })
        wx.showToast({
          title: '您并未修改',
          icon: 'none',
        })
        return
      }
      feedApi
        .editorTheme(theme.id, { title, description })
        .then(() => {
          wx.showToast({
            title: '修改成功',
            duration: 1000,
          })
          setTimeout(() => {
            wx.navigateBack({
              delta: 1,
            })
          }, 1000)
          const themeData = theme
          themeData.title = title
          themeData.description = description
          $event.emit('editorTheme', themeData)
        })
        .catch((err) => {
          wx.showToast({
            title: `${err.massage}`,
            icon: 'none',
          })
          this.setData({
            publishing: true,
          })
        })
    }
  },
})
